<?php

namespace addons\booking\controller;

use addons\booking\library\Theme;
use think\Config;
use think\Hook;
use addons\booking\model\Feedback;
use addons\booking\model\Navigation;
use fast\Http;

/**
 * 公共
 */
class Common extends Base
{
    protected $noNeedLogin = ['init', 'mapSearch', 'staticMap', 'staticAmap', 'getWxCode'];

    /**
     * 初始化
     */
    public function init()
    {
        //配置信息
        $upload = Config::get('upload');

        //如果非服务端中转模式需要修改为中转
        if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
            //临时修改上传模式为服务端中转
            set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

            $upload = \app\common\model\Config::upload();
            // 上传信息配置后
            Hook::listen("upload_config_init", $upload);

            $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
        }

        $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
        $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

        $data = [
            'upload'    => $upload,
            '__token__' => $this->request->token()
        ];

        $swiperInfo = Config::get('booking.swiperInfo');
        $swiperInfo = $swiperInfo ? (array)json_decode($swiperInfo, true) : [];
        foreach ($swiperInfo as $key => &$info) {
            $info['image'] = cdnurl($info['image'], true);
        }
        $data['swiper'] = $swiperInfo;

        $data['order_timeout'] = Config::get('booking.order_timeout');
        $data['notice'] = Config::get('booking.notice');
        $data['distance_checkin_time'] = Config::get('booking.distance_checkin_time');
        $data['money_score'] = Config::get('booking.money_score');
        $data['comment_score'] = Config::get('booking.comment_score');
        $data['category_mode'] = Config::get('booking.category_mode');
        $data['agreement'] = Config::get('booking.agreement');

        $data['navigate'] = Navigation::tableList();

        //站点名称
        $data['sitename'] = config('site.name');

        //消息订阅模板id
        $data['tpl_ids'] = \addons\booking\model\TemplateMsg::getTplIds();

        //合并主题样式，判断是否预览模式
        $isPreview = stripos($this->request->SERVER("HTTP_REFERER"), "mode=preview") !== false;
        $themeConfig = $isPreview && \think\Session::get("previewtheme-booking") ? \think\Session::get("previewtheme-booking") : Theme::get();

        $themeConfig = Theme::render($themeConfig);
        $data = array_merge($data, $themeConfig);

        $this->success('', $data);
    }

    /**
     * 地图周边搜索
     */
    public function mapSearch()
    {
        $url = 'https://apis.map.qq.com/ws/place/v1/search';
        $key = Config::get('booking.qq_map_key');
        if (!$key) {
            $this->error("请在后台配置腾讯地图KEY");
        }
        $data['orderby'] = '_distance';
        $data['page_size'] = 20;
        $data['key'] = $key;
        $data['keyword'] = $this->request->param('keyword');
        $data['page_index'] = $this->request->param('page');
        $latitude = $this->request->param('latitude');
        $longitude = $this->request->param('longitude');
        $category = $this->request->param('category');
        $data['boundary'] = "nearby({$latitude},{$longitude},1000)";
        // $filter = c("category={$category}");
        $str = http_build_query($data);
        $url .= '?' . $str;
        $result = (new Http())->get($url, '', [CURLOPT_REFERER => $url]);
        $result = (array)json_decode($result, true);
        if (isset($result['status']) && $result['status'] == 0) {
            $this->success('', $result);
        }
        $this->error('获取失败', $result);
    }

    /**
     * 反馈
     */
    public function feedback()
    {
        $content = $this->request->post('content');
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        if (empty($content)) {
            $this->error('请填写反馈内容');
        }
        $status = (new Feedback)->save(['user_id' => $this->auth->id, 'content' => $content]);
        if ($status) {
            $this->success('提交成功，感谢您反馈！');
        }
        $this->error('提交失败');
    }

    /**
     * 获取小程序码
     */
    public function getWxCode()
    {
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $user_id = $this->auth->isLogin() ? $this->auth->id : '';
        $resource = '';
        $fileStream = (new \addons\booking\library\Wechat\Service)->getWxCodeUnlimited([
            'scene' => "invite_id={$user_id}&id={$id}",
            'page'  => $type ? 'pages/goods/detail' : 'pages/hotel/detail'
        ]);
        if (is_null(json_decode($fileStream))) {
            try {
                $img = imagecreatefromstring($fileStream);
                ob_start();
                imagepng($img);
                $resource = ob_get_clean();
            } catch (\Exception $e) {
                \think\Log::write($e->getMessage());
                $this->error("获取微信二维码失败！");
            }
        } else {
            $config = get_addon_config('booking');
            if ($config['wxapp']) {
                $localFile = ROOT_PATH . 'public' . $config['wxapp'];
                if (is_file($localFile)) {
                    $resource = file_get_contents($localFile);
                } else {
                    $resource = Http::get(cdnurl($config['wxapp'], true));
                }
            }
        }
        if (!$resource) {
            $this->error("获取二维码失败！");
        }
        $base64_data = base64_encode($resource);
        $base64_file = 'data:image/jpg;base64,' . $base64_data;
        $this->success('获取成功', $base64_file);
    }

}
